import {
  HttpException,
  MiddlewareConsumer,
  Module,
  NestModule,
} from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import * as path from 'path';
import { ConfigModule } from '@nestjs/config';
import { CacheModule } from './cache/cache.module';
import { SmsModule } from './sms/sms.module';
import { UploadModule } from './upload/upload.module';
import { TencentImModule } from './tencent-im/tencent-im.module';
import { UserModule } from './user/user.module';
import { AuthModule } from './auth/auth.module';
import * as cors from 'cors';
import { APP_FILTER } from '@nestjs/core';
const isProd = process.env.NODE_ENV == 'production';

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: [isProd ? path.resolve('.env.prod') : path.resolve('.env')],
    }),
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: process.env.DB_HOST,
      port: parseInt(process.env.DB_PORT),
      username: process.env.DB_USER,
      password: process.env.DB_PSWD,
      database: process.env.DB_DATABASE,
      synchronize: !isProd,
      autoLoadEntities: true,
    }),
    CacheModule,
    SmsModule,
    UploadModule,
    TencentImModule,
    UserModule,
    AuthModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_FILTER,
      useClass: HttpException,
    },
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer): any {
    consumer.apply(cors()).forRoutes('*');
  }
}
